package com.wili.insertLog;
import java.io.File;
import java.io.Serializable;
import com.c.Ca;
import com.wili.c.File9;
/**
 * Serializable configuration. 配置文件在运行时会积累变化。
 * 	配置文件一般都是单实例，但项目有多种配置文件。
 * @author weila 2021年2月13日
 */
public abstract class FileConfig implements Serializable {
	private static final long serialVersionUID = 1L;

	public final File toFile;

	int savedVersion, curVersion;
	protected FileConfig(File file, int saveInterval) {
		//new Exception("").printStackTrace();
		this.toFile = file;
		if ("".isEmpty())
			return;
		Thread mainTrhead = Thread.currentThread();
		if (saveInterval > 0) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					int interval = saveInterval * 1000;
					try {
						while (true) {
							Thread.sleep(interval);
							if (!mainTrhead.isAlive())
								return;
							if (savedVersion < curVersion) {
								saveConfigFile();
								savedVersion = curVersion;
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();
			Runtime.getRuntime().addShutdownHook(new Thread() {
				public void start() {
					savedVersion = curVersion;
					saveConfigFile();
				}
			});
		}
	}

	protected abstract void setInst(FileConfig inst);

	public void updated() {
		++curVersion;
	}

	public void readConfigFile() {
		FileConfig ret = File9.readObject(toFile, null, "");
		this.setInst(ret);
	}

	public void saveConfigFile() {
		savedVersion = curVersion;
		File9.writeObject(this, toFile, -1);
		if (++inc == 23)
			Ca.pause();
		Ca.info(1, inc + ",FileConfig.saveConfigFile:" + toFile.getAbsolutePath());
	}
	int inc234;

	static int inc;
}
